package com.czy.server;

import com.czy.model.Request;
import com.czy.model.Response;
import com.czy.utils.IoCloseUtil;

import java.io.IOException;
import java.net.Socket;

/**
 * 一个请求与响应就是一个Dispatcher
 * @author czy
 * @date 2021-5-26 17:37
 */
public class Dispatcher implements Runnable{
    private Request req;
    private Response rep;
    private Socket client;

    //状态码
    private int code=200;

    //构造方法初始化属性
    public Dispatcher(Socket client) {
        //将局部变量的值赋给成员变量
        this.client=client;
        try {
            req=new Request(this.client.getInputStream());
            rep=new Response(this.client.getOutputStream());
        } catch (IOException e) {
            code=500;
            return ;
        }
    }
    @Override
    public void run() {
        //根据不同的url创建指定的Servlet对象
        //System.out.println(req.getUrl());
        Servlet servlet=WebApp.getServlet(req.getUrl());
        if (servlet==null) {
            this.code=404;
        }else{
            //调用相应的Servlet中的service方法
            try {
                servlet.service(req,rep);
            } catch (Exception e) {
                this.code=500;
            }
        }
        //将响应结果推送到客户机的浏览器
        rep.pushToClient(code);
        IoCloseUtil.closeAll(client);
    }
}
